<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AgricGoods extends Model
{
    use SoftDeletes;
    protected $table = 'agric_goods';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];


    protected $fillable = ['seller_id'];

    protected $appends = ['region_name', 'goods_img_url', 'slider_img_url', 'goods_label_data'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    /**
     * 卖家信息一对一关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function seller_info(){
        return $this->hasOne(AgricGoodsSeller::class,'id','seller_id');
    }

    /**
     * 商品详情信息一对一关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function goods_descriptions(){
        return $this->hasOne(AgricGoodsDescription::class,'goods_id','id');
    }

    public function getGoodsImgUrlAttribute()
    {
        return config('app.img_url') . $this->goods_img;
    }

    public function getGoodsLabelDataAttribute()
    {
        return json_decode($this->goods_label, true);
    }

    public function setGoodsLabelAttribute($goods_label)
    {
        $this->attributes['goods_label'] = json_encode(array_values($goods_label));
    }

    public function getRegionNameAttribute()
    {
        return SystemRegion::where('id',$this->attributes['region_id']) -> value('region_name');
    }

    public function getSliderImgUrlAttribute()
    {
        $newarr = [];
        if($this -> attributes['slider_img']){
            $arr = json_decode($this -> attributes['slider_img']);
            foreach($arr as $v){
                $newarr[] = config('app.img_url') . $v;
            }
        }
        return $newarr;
    }

    /*
     * 获取某类商品列表
     * */
    public static function getAgricGoods($request){

        $pagesize = $request -> input('pagesize') ?? '5';
        if($request -> filled('category_id')){
            // 判断此类型是否可用
            if( AgricGoodsCategory::where('id',$request -> input('category_id')) ->value('status')){
                $category_ids = [$request -> input('category_id')];
            }else{
                return false;
            }
        }else{
            $category_ids = AgricGoodsCategory::where('status','1') -> pluck('id') -> toArray();
        }
        $res = self::with(['seller_info:id,seller_name,seller_num,head_portrait'])
            -> whereIn('category_id',$category_ids) -> paginate($pagesize);

        return $res;
    }

    /*
     * 详情页
     * */
    public static function getDetails($id)
    {

        $res = AgricGoods::with(['seller_info:id,seller_name,seller_num,head_portrait,wx',
            'goods_descriptions:goods_id,goods_description'])
            -> find($id);

        return $res;
    }


    /*
     * 商品操作类型 感兴趣1、查看卖家微信2，查看手机号3，点击数4
     * */
    public static function agricGoodsOperated($goods_id, $type)
    {

        $data = [
            'goods_id'     => $goods_id,
            'user_id'      => auth() -> id(),
            'operate_type' => $type,
        ];


        switch($type){
            case 1:

                if($agricGoodsOperateLog = AgricGoodsOperateLog::where($data) -> first()){
                    $operated = true;
                    $agricGoodsOperateLog -> delete();
                }else{
                    $operated = false;
                    AgricGoodsOperateLog::create($data);
                }
                $collect_data = [
                    'obj_id' => $goods_id,
                    'obj_types' =>  2,
                    'types' =>  1
                ];
                $res = UserCollect::up($collect_data);
                break;
            case 2:case 3:
                $res = AgricGoodsOperateLog::create($data);
                break;
            case 4:
                AgricGoodsOperateLog::create($data);
                $res = self::where('id',$goods_id) -> increment('hit_num');
                break;

        }

        return $res;
    }

    /**
     * pc端农品热销栏目
     * @param int $number
     * @return mixed
     */
    public static function pc_hot_goods_list($number = 4)
    {
        $hotGoods = AgricGoods::where('is_show', 1)
            ->orderBy('sales_num', 'desc')
            ->orderBy('id', 'desc')
            ->take($number)
            ->get(['id', 'goods_name', 'goods_img', 'acticity_price', 'goods_price', 'region_id', 'slider_img']);

        return $hotGoods;
    }
}
